﻿using Exam.infranstuctrue.Dto.other;
using Exam.infranstuctrue.Dto.Request.Task;
using Exam.infranstuctrue.Dto.Respones;
using Exam.infranstuctrue.Dto.Respones.statistics;
using Exam.infranstuctrue.Dto.Respones.Task;
using Exam.infranstuctrue.EFCore;
using Exam.infranstuctrue.IOC;
using Exam.infranstuctrue.Tools;
using Exam.infranstuctrue.Tools.Attributes;
using Exam.Infrastrucrure.Dto;
using Exam.Service.Interface;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace Exam.Service.Instance
{
    [Iinjection]
    public class TaskServer : BaseService, ITaskServer
    {
        private readonly ExerciseIOC _exerciseIOC;
        private readonly ExamIOC _examIOC;

        public TaskServer(ExerciseIOC exerciseIOC, ExamIOC examIOC)
        {
            _exerciseIOC = exerciseIOC;
            _examIOC = examIOC;
        }
        /// <summary>
        /// 获取组织
        /// </summary>
        /// <param name="organizationids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetOrg(string organizationids, string? token = null)
        {
            string orgname = "";
            var url = "https://change.qiudaoyu.top/api/Organization/GetOrganization";
            var res = Http.Get(url, token);
            var returns = JsonConvert.DeserializeObject<ApiResult>(res);
            var result = JsonConvert.SerializeObject(returns.data);
            var data = JsonConvert.DeserializeObject<List<OrganizationDto>>(result);

            var orgids = data.Select(d => d.id).ToList();
            if (!string.IsNullOrEmpty(organizationids))
            {

                var orgIds = organizationids.Split(",");
                orgname = "";
                foreach (var item2 in orgIds)
                {
                    var iq = data.Where(d => d.id == item2).FirstOrDefault();//得到组织
                    if (iq != null)
                    {
                        orgname += iq.name + ",";
                    }
                    else
                    {
                        var chilre = data.Select(d => d.children).ToList();
                        foreach (var item3 in chilre)
                        {
                            var iq2 = item3.Where(d => d.id == item2).FirstOrDefault();
                            if (iq2 != null)
                            {
                                orgname += iq2.name + ",";
                            }
                        }

                    }
                }
                orgname = orgname.Substring(0, orgname.Length - 1);
            }
            return orgname;
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="orgabizationuids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetUser(string orgabizationuids, string? token = null)
        {
            var uname = "";
            var url = "https://change.qiudaoyu.top/api/Admin/GetUser/?page=1&&limit=99999";
            var users = Http.Get(url, token);
            var user = JsonConvert.DeserializeObject<MyApiResult>(users);
            var userchilren = JsonConvert.SerializeObject(user.data);
            var result = JsonConvert.DeserializeObject<MyApiResultChliren>(userchilren);
            var res = JsonConvert.SerializeObject(result.data);
            var data = JsonConvert.DeserializeObject<List<ResponseAdminDto>>(res);

            var uids = data.Select(d => d.id).ToList();
            if (!string.IsNullOrEmpty(orgabizationuids))
            {

                var uid = orgabizationuids.Split(",");
                uname = "";
                foreach (var item2 in uid)
                {
                    var iq = data.Where(d => d.id == item2).Single();
                    uname += iq.name + ",";
                }
                uname = uname.Substring(0, uname.Length - 1);
            }
            return uname;
        }
        /// <summary>
        /// 通过组织获取用户
        /// </summary>
        /// <param name="oid"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private List<ResponseAdminDto> GetOrgToUser(string oid, string? token = null)
        {
            var list = new List<ResponseAdminDto>();
            var oids = oid.Split(",");
            foreach (var item in oids)
            {
                var url = "https://change.qiudaoyu.top/api/Organization/GetOrganizationUser?oid=" + item + "&&page=1&&limit=9999";
                var result = Http.Get(url, token);
                var res = JsonConvert.DeserializeObject<MyApiResult>(result);
                var data = JsonConvert.SerializeObject(res.data);
                var datas = JsonConvert.DeserializeObject<MyApiResultChliren>(data);
                var uids = JsonConvert.SerializeObject(datas.data);
                var results = JsonConvert.DeserializeObject<List<ResponseAdminDto>>(uids);
                list.AddRange(results);
            }

            return list;
        }
        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="page"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetTask(string? token = "", int page = 1, int limit = 10, string? key = "")
        {
            var task = await _exerciseIOC._examTaskEFCore.QueryAll(out int total, page, limit, o => o.TbeginTime, false, d => d.Tlabels.Contains(key)).ToListAsync();
            var tids = task.Select(d => d.Tid).ToList();
            var taskdetalis = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => 1 == 1).ToListAsync();
            List<TaskRes> taskRes = new List<TaskRes>();
            foreach (var item in task)
            {
                //var taskdetali = taskdetalis.Where(d => d.Tdtid.Contains(item.Tid)).ToList();
                //List<TaskDetaliRes> taskDetaliRes = new List<TaskDetaliRes>();
                //foreach (var item2 in taskdetali)
                //{
                //    taskDetaliRes.Add(new TaskDetaliRes
                //    {
                //        Tdid = item2.Tdid,
                //        TdbeginTime = item2.TdbeginTime,
                //        TdendTime = item2.TdendTime,
                //        TdisComplete = item2.TdisComplete,
                //        Tdpercent = item2.Tdpercent,
                //        Tdtid = item2.Tdtid,
                //        Tduid = GetUser(item2.Tduid, token),

                //    });
                //}
                taskRes.Add(new TaskRes
                {
                    Tid = item.Tid,
                    Tcount = item.Tcount,
                    Tcourses = item.Tcourses,
                    Tcycle = item.Tcycle,
                    TbeginTime = item.TbeginTime,
                    TendTime = item.TendTime,
                    Tlabels = item.Tlabels,
                    TmaxLv = item.TmaxLv,
                    TminLv = item.TminLv,
                    TorgIds = GetOrg(item.TorgIds, token),
                    TtrainId = item.TtrainId,
                    TisTrain = item.TisTrain,
                    //taskdetali= taskDetaliRes
                });
            }
            return GetResult(1, "所有任务", data: (new
            {
                total = total,
                data = taskRes
            }));
        }
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddTask(TaskDto dto)
        {
            List<string> adminDtos = new List<string>();
            var uids = GetOrgToUser(dto.TorgIds, dto.token).ToList();
            uids.ForEach(e =>
            {
                if (!adminDtos.Contains(e.id))
                {
                    adminDtos.Add(e.id);
                }
            });

            var tid = Config.GUID();
            ExamTask examTask = new ExamTask()
            {
                Tid = tid,
                TbeginTime = dto.TbeginTime,
                Tcount = dto.Tcount,
                Tcourses = dto.Tcourses,
                Tcycle = dto.Tcycle,
                Tdesc = "",
                TendTime = dto.TendTime,
                Tlabels = dto.Tlabels,
                TmaxLv = dto.TmaxLv,
                TminLv = dto.TminLv,
                TisTrain = dto.TisTrain,
                TtrainId = dto.TtrainId,
                TorgIds = dto.TorgIds,
            };
            List<ExamTaskDetail> examTaskDetails = new List<ExamTaskDetail>();
            foreach (var item in adminDtos)
            {
                examTaskDetails.Add(new ExamTaskDetail
                {
                    Tdid = Config.GUID(),
                    Tddesc = "",
                    TdbeginTime = null,
                    TdendTime = null,
                    TdisComplete = 0,
                    Tdpercent = 0,
                    Tdtid = tid,
                    Tduid = item,
                });
            }
            _exerciseIOC._examTaskEFCore.Add(examTask);
            _exerciseIOC._examTaskDetailEFCore.AddRange(examTaskDetails);
            var task = await _exerciseIOC._examTaskEFCore.SaveChangesAsync();
            var taskdetali = await _exerciseIOC._examTaskDetailEFCore.SaveChangesAsync();
            return GetResult(task > 0 ? 1 : 0, task > 0 ? "添加成功" : "添加失败");
        }
        /// <summary>
        /// 获取单个任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateEchoTask(string tid, string? token = null)
        {
            var task = await _exerciseIOC._examTaskEFCore.QueryAll(d => d.Tid == tid).FirstOrDefaultAsync();
            if (task == null)
            {
                return GetResult(0, "参数错误");
            }
            var taskdetalis = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tdtid == tid).ToListAsync();
            List<TaskDetaliRes> taskDetaliRes = new List<TaskDetaliRes>();
            foreach (var item in taskdetalis)
            {
                taskDetaliRes.Add(new TaskDetaliRes
                {
                    tduname = GetUser(item.Tduid, token),
                    Tduid = item.Tduid,
                    TdbeginTime = item.TdbeginTime,
                    TdendTime = item.TdendTime,
                    TdisComplete = item.TdisComplete,
                    Tdpercent = item.Tdpercent,
                    Tdid = item.Tdid,
                    Tdtid = item.Tdtid,
                });
            }
            TaskRes taskRes = new TaskRes()
            {
                Tid = task.Tid,
                TbeginTime = task.TbeginTime,
                Tcount = task.Tcount,
                Tcourses = task.Tcourses,
                Tcycle = task.Tcycle,
                TendTime = task.TendTime,
                TisTrain = task.TisTrain,
                Tlabels = task.Tlabels,
                TmaxLv = task.TmaxLv,
                TminLv = task.TminLv,
                TtrainId = task.TtrainId,
                TorgIds = task.TorgIds,
                Torgname = GetOrg(task.TorgIds, token),
                taskdetali = taskDetaliRes,
            };
            return GetResult(1, "单个任务", taskRes);
        }
        /// <summary>
        /// 修改任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateTask(TaskDto dto)
        {
            var task = await _exerciseIOC._examTaskEFCore.QueryAll(d => d.Tid == dto.Tid).FirstOrDefaultAsync();
            if (task.TbeginTime < DateTime.Now)
            {
                return GetResult(0, "任务已开始不可修改");
            }
            if (dto.TorgIds != null)
            {
                var taskdetali = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tdtid == dto.Tid).ToListAsync();
                List<string> adminDtos = new List<string>();
                var uids = GetOrgToUser(dto.TorgIds, dto.token).ToList();
                uids.ForEach(e =>
                {
                    if (!adminDtos.Contains(e.id))
                    {
                        adminDtos.Add(e.id);
                    }
                });
                //List<ExamTaskDetail> examTaskDetails = new List<ExamTaskDetail>();
                foreach (var item in adminDtos)
                {
                    foreach (var item2 in taskdetali)
                    {
                        item2.Tduid = item;
                    }
                }
                _exerciseIOC._examTaskDetailEFCore.UpdateRange(taskdetali);
                _exerciseIOC._examTaskDetailEFCore.SaveChanges();
            }
            task.TisTrain = dto.TisTrain;
            task.TorgIds = dto.TorgIds;
            task.Tcount = dto.Tcount;
            task.TbeginTime = dto.TbeginTime;
            task.TendTime = dto.TendTime;
            task.Tcourses = dto.Tcourses;
            task.Tlabels = dto.Tlabels;
            task.Tcycle = dto.Tcycle;
            _exerciseIOC._examTaskEFCore.Update(task);
            var result = _exerciseIOC._examTaskEFCore.SaveChanges();
            return GetResult(result > 0 ? 1 : 0, result > 0 ? "修改成功" : "修改失败");
        }
        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteTask(string tid, string? token = null)
        {
            var task = await _exerciseIOC._examTaskEFCore.QueryAll(d => d.Tid == tid).FirstOrDefaultAsync();
            if (task == null)
            {
                return GetResult(0, "参数错误");
            }
            if (task.TbeginTime < DateTime.Now)
            {
                return GetResult(0, "任务已开始不可修改");
            }
            var taskdetali = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tdtid == tid).ToListAsync();
            _exerciseIOC._examTaskEFCore.Delete(task);
            _exerciseIOC._examTaskDetailEFCore.DeleteRange(taskdetali);
            var result = _exerciseIOC._examTaskEFCore.Transactions(_exerciseIOC._examTaskEFCore, _exerciseIOC._examTaskDetailEFCore);
            return GetResult(result == true ? 1 : 0, result == true ? "删除成功" : "删除失败");
        }
        /// <summary>
        /// 统计
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> TaskPaper()
        {
            var testpaper = await _examIOC._examTestPaperEFCore.QueryAll(d => 1 == 1).ToListAsync();

            var useranswer = await _examIOC._examUserAnswerEFCore.QueryAll(d => 1 == 1).ToListAsync();

            var questionbank = await _examIOC._examQuestionBankEFCore.QueryAll(d => 1 == 1).ToListAsync();

            var question = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qtype == 1).ToListAsync();

            var mquestion = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qtype == 2).ToListAsync();

            var equestion = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qtype == 3).ToListAsync();

            statisticsRes statisticsRes = new statisticsRes();
            statisticsRes.TaskPaperCount = testpaper.Count();
            statisticsRes.ExamCount = useranswer.Count();
            statisticsRes.QuestionBank = questionbank.Count();
            statisticsRes.Cquestion = question.Count();
            statisticsRes.Mquesiotn = mquestion.Count();
            statisticsRes.Equestion = equestion.Count();
            return GetResult(1, "统计", statisticsRes);
        }
        /// <summary>
        ///难度统计
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> QuestionLv()
        {
            var one = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 1).ToListAsync();
            var two = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 2).ToListAsync();
            var three = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 3).ToListAsync();
            var four = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 4).ToListAsync();
            var five = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 5).ToListAsync();
            var six = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 6).ToListAsync();
            var senven = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 7).ToListAsync();
            var eight = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 8).ToListAsync();
            var nine = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 9).ToListAsync();
            var ten = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qlv == 10).ToListAsync();
            statisticsRes statisticsRes = new statisticsRes();
            statisticsRes.one = one.Count();
            statisticsRes.two = two.Count();
            statisticsRes.three = three.Count();
            statisticsRes.four = four.Count();
            statisticsRes.five = five.Count();
            statisticsRes.sex = six.Count();
            statisticsRes.senven = senven.Count();
            statisticsRes.eight = eight.Count();
            statisticsRes.nine = nine.Count();
            statisticsRes.ten = ten.Count();
            return GetResult(1, "难度统计",statisticsRes);
        }
    }
}
